package com.aishare.qicaitaoke.network;

import com.aishare.qicaitaoke.utils.KLog;
import com.aishare.qicaitaoke.utils.klog.LogInterceptor;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 作者luwenming
 * 时间2018/1/31
 */

public class NetWork {
    private static String baseUrl;
    private static OkHttpClient okHttpClient;
    private static Converter.Factory gsonConverter = GsonConverterFactory.create();
    private static CallAdapter.Factory rxCallAdapter = RxJavaCallAdapterFactory.create();
    private static Retrofit retrofit;

    static {
        if(KLog.debug) {
            baseUrl = "";
        }else {
            baseUrl = "";
        }
    }

    private static Retrofit getRetrofit(){
        if(retrofit==null){
            retrofit = new Retrofit.Builder().client(getOkHttpClient()).baseUrl(baseUrl)
            .addConverterFactory(gsonConverter)
            .addCallAdapterFactory(rxCallAdapter)
            .build();
        }
        return retrofit;
    }

    private static OkHttpClient getOkHttpClient(){
        if(okHttpClient==null){
            OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
            if(KLog.debug){
                HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                builder.addInterceptor(new LogInterceptor());
            }
            builder.addNetworkInterceptor(new CreateInterceptor());
            okHttpClient = builder.build();
        }
        return okHttpClient;
    }

    public static ApiService getApiService(){
        return getRetrofit().create(ApiService.class);
    }

}
